package com.dnndo.common.utils.oss;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;

/**
 * OssClientHolder
 */
public class OssClientHolder {
    private static volatile OSS ossClient;
    private static String endpoint;
    private static String accessKeyId;
    private static String accessKeySecret;
    public static synchronized void init(String endpoint, String accessKeyId, String accessKeySecret) {
        OssClientHolder.endpoint = endpoint;
        OssClientHolder.accessKeyId = accessKeyId;
        OssClientHolder.accessKeySecret = accessKeySecret;
        if (ossClient == null) {
            ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        }
    }

    // 双重检查锁实现
    public static OSS getInstance() {
        if (ossClient == null) {
            synchronized (OssClientHolder.class) {
                if (ossClient == null) {
                    if (endpoint == null || accessKeyId == null || accessKeySecret == null) {
                        throw new IllegalStateException("OSS credentials not initialized");
                    }
                    ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
                }
            }
        }
        return ossClient;
    }

    public static synchronized void shutdown() {
        if (ossClient != null) {
            ossClient.shutdown();
            ossClient = null;
        }
    }
}
